package cn.org.donald.sensitive.model;

import com.itextpdf.awt.geom.Rectangle2D;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Donald
 * @since 2023-11-14 09:51:57
 **/
public class KeyWordPositionListener implements RenderListener {


    private final Integer currentPage;

    private final Rectangle rectangle;

    private final String keyword;

    private final List<PdfMatchItem> matches = new ArrayList<>();
    private final List<PdfMatchItem> allItems = new ArrayList<>();

    public KeyWordPositionListener(Integer currentPage, Rectangle rectangle, String keyword) {
        this.currentPage = currentPage;
        this.rectangle = rectangle;
        this.keyword = keyword;
    }

    @Override
    public void beginTextBlock() {
        // TODO  Do nothing
    }

    @Override
    public void renderText(TextRenderInfo textRenderInfo) {
        String text = textRenderInfo.getText();
        Rectangle2D.Float boundingRectange = textRenderInfo.getDescentLine().getBoundingRectange();
        // 获取字符
        PdfMatchItem pdfMatchItem = new PdfMatchItem();
        pdfMatchItem.setContent(text);
        pdfMatchItem.setCurrentPage(currentPage);
        pdfMatchItem.setFontHeight(boundingRectange.height == 0 ? 12 : boundingRectange.height);
        pdfMatchItem.setFontWidth(boundingRectange.width);
        pdfMatchItem.setPageHeight(rectangle.getHeight());
        pdfMatchItem.setPageWidth(rectangle.getWidth());
        pdfMatchItem.setX((float) boundingRectange.getX());
        pdfMatchItem.setY((float) boundingRectange.getY());
        if (text.equalsIgnoreCase(keyword)) {
            matches.add(pdfMatchItem);
        }
        allItems.add(pdfMatchItem);
    }

    @Override
    public void endTextBlock() {
        // TODO  Do nothing

    }

    @Override
    public void renderImage(ImageRenderInfo imageRenderInfo) {
        // TODO  Do nothing

    }

    public List<PdfMatchItem> getMatches() {
        return matches;
    }

    public List<PdfMatchItem> getAllItems() {
        return allItems;
    }
}
